package com.youhome.controller;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.youhome.config.OSSConfig;
import com.youhome.entity.*;
import com.youhome.model.*;
import com.youhome.response.Result;
import com.youhome.response.ResultCode;
import com.youhome.response.ResultPage;
import com.youhome.service.*;
import com.youhome.utils.DoubleUtils;
import com.youhome.utils.OSSUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by chen365 on 2018/05/09.
 */
@RestController
@RequestMapping(value = "/house/")
@Api(tags = "房源")
public class HouseController {

    @Autowired
    private HouseService houseService;

    @Autowired
    private ListHubPhotoService listHubPhotoService;

    @Autowired
    private SolrService solrService;

    @Autowired
    private HotCityService hotCityService;

    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private DownloadService downloadService;

    @Autowired
    private TranslateService translateService;

    @Autowired
    private HouseVideoService houseVideoService;

    @Autowired
    private HousePropertySubTypeService housePropertySubTypeService;

    @ApiOperation(value = "房源类型", notes = "房源类型", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @GetMapping(value = "/subType")
    public Object subType() {
        List<HousePropertySubType> subTypes = housePropertySubTypeService.selectByAll();
        if (subTypes != null && subTypes.size() > 0) {
            return new Result<>(ResultCode.SUCCESS, subTypes);
        }
        return new Result<>(ResultCode.FAIL);
    }


    @ApiOperation(value = "房源详情", notes = "房源详情", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "houseId", value = "房源ID", required = true, paramType = "path")
    })
    @GetMapping(value = "/{houseId}/details")
    public Object details(@PathVariable("houseId") String houseId) {
        return new Result<>(ResultCode.SUCCESS);
    }

    @ApiOperation(value = "房源特征", notes = "房源特征", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "houseId", value = "房源ID", required = true, paramType = "path")
    })
    @GetMapping(value = "/{houseId}/characteristics")
    public Object characteristics(@PathVariable("houseId") String houseId) {
        House listHub = houseService.selectByPrimaryKey(houseId);
        if (listHub != null) {
            if (!StringUtils.isEmpty(listHub.getListingKey())) {
                String key = "json/" + listHub.getListingKey() + ".json";
                try {
                    String json = downloadService.downloadJsonFromOSS(key);
                    if (!StringUtils.isEmpty(json)) {
                        JSONObject jsonObject = JSONObject.parseObject(json);
                        ObjectMapper mapper = new ObjectMapper();
                        //房源特征
                        if (jsonObject.get("detailedCharacteristics") != null && !jsonObject.get("detailedCharacteristics").equals("null")) {
                            JSONObject characteristics = (JSONObject) jsonObject.get("detailedCharacteristics");
                            if (characteristics != null && !characteristics.equals("null")) {
                                DetailedCharacteristicsType detailedCharacteristicsType = mapper.readValue(characteristics.toString(), DetailedCharacteristicsType.class);

                                Characteristics detailedCharacteristics = new Characteristics();
                                //电器
                                if (detailedCharacteristicsType.getAppliances() != null && !detailedCharacteristicsType.getAppliances().equals("null")) {
                                    if (detailedCharacteristicsType.getAppliances().getAppliance() != null && !detailedCharacteristicsType.getAppliances().getAppliance().equals("null")) {
                                        List<ApplianceEnum> appliance = detailedCharacteristicsType.getAppliances().getAppliance();
                                        ArrayList<String> appliances = new ArrayList<>();
                                        for (ApplianceEnum item : appliance) {
                                            if (!StringUtils.isEmpty(item.getValue())) {
                                                appliances.add(item.getValue());
                                            }
                                        }
                                        detailedCharacteristics.setAppliances(appliances);
                                    }
                                }
                                //建筑风格
                                if (detailedCharacteristicsType.getArchitectureStyle() != null && !detailedCharacteristicsType.getArchitectureStyle().equals("null")) {
                                    String architectureStyle = detailedCharacteristicsType.getArchitectureStyle().getValue();
                                    //detailedCharacteristics.setArchitecture_style(architectureStyle);
                                }


                                //制冷系统
                                if (detailedCharacteristicsType.getCoolingSystems() != null && !detailedCharacteristicsType.getCoolingSystems().equals("null")) {
                                    if (detailedCharacteristicsType.getCoolingSystems().getCoolingSystem() != null && !detailedCharacteristicsType.getCoolingSystems().getCoolingSystem().equals("null")) {
                                        List<CoolingSystemEnum> coolingSystem = detailedCharacteristicsType.getCoolingSystems().getCoolingSystem();
                                        ArrayList<String> coolingSystems = new ArrayList<>();
                                        for (CoolingSystemEnum item : coolingSystem) {
                                            if (!StringUtils.isEmpty(item.getValue())) {
                                                coolingSystems.add(item.getValue());
                                            }
                                        }
                                        detailedCharacteristics.setCooling_systems(coolingSystems);
                                    }
                                }

                                //室外装修
                                if (detailedCharacteristicsType.getExteriorTypes() != null && !detailedCharacteristicsType.getExteriorTypes().equals("null")) {
                                    if (detailedCharacteristicsType.getExteriorTypes().getExteriorType() != null && !detailedCharacteristicsType.getExteriorTypes().getExteriorType().equals("null")) {
                                        List<ExteriorFinishEnum> exteriorType = detailedCharacteristicsType.getExteriorTypes().getExteriorType();
                                        ArrayList<String> exteriorTypes = new ArrayList<>();
                                        for (ExteriorFinishEnum item : exteriorType) {
                                            if (!StringUtils.isEmpty(item.getValue())) {
                                                exteriorTypes.add(item.getValue());
                                            }
                                        }
                                        detailedCharacteristics.setExterior_types(exteriorTypes);
                                    }
                                }


                                //地板
                                if (detailedCharacteristicsType.getFloorCoverings() != null && !detailedCharacteristicsType.getFloorCoverings().equals("null")) {
                                    if (detailedCharacteristicsType.getFloorCoverings().getFloorCovering() != null && !detailedCharacteristicsType.getFloorCoverings().getFloorCovering().equals("null")) {
                                        List<FlooringMaterialEnum> floorCovering = detailedCharacteristicsType.getFloorCoverings().getFloorCovering();
                                        ArrayList<String> floorCoverings = new ArrayList<>();
                                        for (FlooringMaterialEnum item : floorCovering) {
                                            if (!StringUtils.isEmpty(item.getValue())) {
                                                floorCoverings.add(item.getValue());
                                            }
                                        }
                                        detailedCharacteristics.setFloor_coverings(floorCoverings);
                                    }
                                }

                                //供暖(燃料)
                                if (detailedCharacteristicsType.getHeatingFuels() != null && !detailedCharacteristicsType.getHeatingFuels().equals("null")) {
                                    if (detailedCharacteristicsType.getHeatingFuels().getHeatingFuel() != null && !detailedCharacteristicsType.getHeatingFuels().getHeatingFuel().equals("null")) {
                                        List<FuelEnum> heatingFuel = detailedCharacteristicsType.getHeatingFuels().getHeatingFuel();
                                        ArrayList<String> heatingFuels = new ArrayList<>();
                                        for (FuelEnum item : heatingFuel) {
                                            if (!StringUtils.isEmpty(item.getValue())) {
                                                heatingFuels.add(item.getValue());
                                            }
                                        }
                                        detailedCharacteristics.setHeating_fuels(heatingFuels);
                                    }
                                }

                                //供暖系统
                                if (detailedCharacteristicsType.getHeatingSystems() != null && !detailedCharacteristicsType.getHeatingSystems().equals("null")) {
                                    if (detailedCharacteristicsType.getHeatingSystems().getHeatingSystem() != null && !detailedCharacteristicsType.getHeatingSystems().getHeatingSystem().equals("null")) {
                                        List<HeatingSystemEnum> heatingSystem = detailedCharacteristicsType.getHeatingSystems().getHeatingSystem();
                                        ArrayList<String> heatingSystems = new ArrayList<>();
                                        for (HeatingSystemEnum item : heatingSystem) {
                                            if (!StringUtils.isEmpty(item.getValue())) {
                                                heatingSystems.add(item.getValue());
                                            }
                                        }
                                        detailedCharacteristics.setHeating_systems(heatingSystems);
                                    }
                                }
                                //车库
                                if (detailedCharacteristicsType.getParkingTypes() != null && !detailedCharacteristicsType.getParkingTypes().equals("null")) {
                                    if (detailedCharacteristicsType.getParkingTypes().getParkingType() != null && !detailedCharacteristicsType.getParkingTypes().getParkingType().equals("null")) {
                                        List<ParkingEnum> parkingType = detailedCharacteristicsType.getParkingTypes().getParkingType();
                                        ArrayList<String> parkingTypes = new ArrayList<>();
                                        for (ParkingEnum item : parkingType) {
                                            if (!StringUtils.isEmpty(item.getValue())) {
                                                parkingTypes.add(item.getValue());
                                            }
                                        }
                                        detailedCharacteristics.setParking_types(parkingTypes);
                                    }
                                }
                                //屋顶类型
                                if (detailedCharacteristicsType.getRoofTypes() != null && !detailedCharacteristicsType.getRoofTypes().equals("null")) {
                                    if (detailedCharacteristicsType.getRoofTypes().getRoofType() != null && !detailedCharacteristicsType.getRoofTypes().getRoofType().equals("null")) {
                                        List<RoofMaterialEnum> roofType = detailedCharacteristicsType.getRoofTypes().getRoofType();
                                        ArrayList<String> roofTypes = new ArrayList<>();
                                        for (RoofMaterialEnum item : roofType) {
                                            if (!StringUtils.isEmpty(item.getValue())) {
                                                roofTypes.add(item.getValue());
                                            }
                                        }
                                        detailedCharacteristics.setRoof_types(roofTypes);
                                    }
                                }

                                //房间
                                if (detailedCharacteristicsType.getRooms() != null && !detailedCharacteristicsType.getRooms().equals("null")) {
                                    if (detailedCharacteristicsType.getRooms().getRoom() != null && !detailedCharacteristicsType.getRooms().getRoom().equals("null")) {
                                        List<RoomCategoryEnum> room = detailedCharacteristicsType.getRooms().getRoom();
                                        ArrayList<String> rooms = new ArrayList<>();
                                        for (RoomCategoryEnum item : room) {
                                            if (!StringUtils.isEmpty(item.getValue())) {
                                                rooms.add(item.getValue());
                                            }
                                        }
                                        //detailedCharacteristics.setRooms(rooms);
                                    }
                                }

                                //视野类型
                                if (detailedCharacteristicsType.getViewTypes() != null && !detailedCharacteristicsType.getViewTypes().equals("null")) {
                                    if (detailedCharacteristicsType.getViewTypes().getViewType() != null && !detailedCharacteristicsType.getViewTypes().getViewType().equals("null")) {
                                        List<ViewEnum> viewType = detailedCharacteristicsType.getViewTypes().getViewType();
                                        detailedCharacteristicsType.getViewTypes().getViewType();
                                        ArrayList<String> viewTypes = new ArrayList<>();
                                        for (ViewEnum item : viewType) {
                                            if (!StringUtils.isEmpty(item.getValue())) {
                                                viewTypes.add(item.getValue());
                                            }
                                        }
                                        detailedCharacteristics.setView_types(viewTypes);
                                    }
                                }

                                detailedCharacteristics.setHas_attic(detailedCharacteristicsType.isHasAttic());
                                //detailedCharacteristics.setHas_barbecue_area(detailedCharacteristicsType.isHasBarbecueArea());
                                detailedCharacteristics.setHas_basement(detailedCharacteristicsType.isHasBasement());
                                //detailedCharacteristics.setBuilding_unit_count(detailedCharacteristicsType.getBuildingUnitCount());
                                detailedCharacteristics.setIs_cable_ready(detailedCharacteristicsType.isIsCableReady());
                                detailedCharacteristics.setHas_ceiling_fan(detailedCharacteristicsType.isHasCeilingFan());
                                detailedCharacteristics.setCondo_floor_num(detailedCharacteristicsType.getCondoFloorNum());
                                detailedCharacteristics.setHas_deck(detailedCharacteristicsType.isHasDeck());
                                detailedCharacteristics.setHas_disabled_access(detailedCharacteristicsType.isHasDisabledAccess());
                                detailedCharacteristics.setHas_dock(detailedCharacteristicsType.isHasDock());
                                detailedCharacteristics.setHas_doorman(detailedCharacteristicsType.isHasDoorman());
                                detailedCharacteristics.setHas_double_pane_windows(detailedCharacteristicsType.isHasDoublePaneWindows());
                                detailedCharacteristics.setHas_elevator(detailedCharacteristicsType.isHasElevator());
                                detailedCharacteristics.setHas_fireplace(detailedCharacteristicsType.isHasFireplace());
                                detailedCharacteristics.setHas_garden(detailedCharacteristicsType.isHasGarden());
                                //detailedCharacteristics.setHas_gated_entry(detailedCharacteristicsType.isHasGatedEntry());
                                detailedCharacteristics.setHas_greenhouse(detailedCharacteristicsType.isHasGreenhouse());
                                detailedCharacteristics.setHas_hot_tub_spa(detailedCharacteristicsType.isHasHotTubSpa());
                                detailedCharacteristics.setIntercom(detailedCharacteristicsType.isIntercom());
                                detailedCharacteristics.setHas_jetted_bath_tub(detailedCharacteristicsType.isHasJettedBathTub());
                                detailedCharacteristics.setHas_lawn(detailedCharacteristicsType.isHasLawn());
                                //detailedCharacteristics.setLegal_description(detailedCharacteristicsType.getLegalDescription());
                                //detailedCharacteristics.setHas_mother_in_law(detailedCharacteristicsType.isHasMotherInLaw());
                                detailedCharacteristics.setIs_new_construction(detailedCharacteristicsType.isIsNewConstruction());
                                detailedCharacteristics.setNum_floors(detailedCharacteristicsType.getNumFloors());
                                detailedCharacteristics.setNum_parking_spaces(detailedCharacteristicsType.getNumParkingSpaces());
                                detailedCharacteristics.setHas_patio(detailedCharacteristicsType.isHasPatio());
                                detailedCharacteristics.setHas_pond(detailedCharacteristicsType.isHasPond());
                                detailedCharacteristics.setHas_pool(detailedCharacteristicsType.isHasPool());
                                detailedCharacteristics.setHas_porch(detailedCharacteristicsType.isHasPorch());
                                // detailedCharacteristics.setRoom_count(detailedCharacteristicsType.getRoomCount());
                                detailedCharacteristics.setHas_rv_parking(detailedCharacteristicsType.isHasRVParking());
                                detailedCharacteristics.setHas_sauna(detailedCharacteristicsType.isHasSauna());
                                detailedCharacteristics.setHas_security_system(detailedCharacteristicsType.isHasSecuritySystem());
                                detailedCharacteristics.setHas_skylight(detailedCharacteristicsType.isHasSkylight());
                                detailedCharacteristics.setHas_sports_court(detailedCharacteristicsType.isHasSportsCourt());
                                detailedCharacteristics.setHas_sprinkler_system(detailedCharacteristicsType.isHasSprinklerSystem());
                                detailedCharacteristics.setHas_vaulted_ceiling(detailedCharacteristicsType.isHasVaultedCeiling());
                                detailedCharacteristics.setIs_water_front(detailedCharacteristicsType.isIsWaterfront());
                                detailedCharacteristics.setHas_wet_bar(detailedCharacteristicsType.isHasWetBar());
                                //detailedCharacteristics.setWhat_owner_loves(detailedCharacteristicsType.getWhatOwnerLoves());
                                detailedCharacteristics.setIs_wired(detailedCharacteristicsType.isIsWired());

                                return new Result(ResultCode.SUCCESS, detailedCharacteristics);
                            }
                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (JsonParseException e) {
                    e.printStackTrace();
                } catch (JsonMappingException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            return new Result(ResultCode.NO_DATA);
        }
        return new Result(ResultCode.SUCCESS);
    }

    @ApiOperation(value = "房源基本信息", notes = "房源基本信息", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "houseId", value = "房源ID", required = true, paramType = "path")
    })
    @GetMapping(value = "/{houseId}/basicInfo")
    public Object basicInfo(@PathVariable("houseId") String houseId) {
        HouseBasicInfo houseBasicInfo = new HouseBasicInfo();

        House listHub = houseService.selectByPrimaryKey(houseId);
        if (listHub != null) {
            houseBasicInfo.setAddress(listHub.getAddress());
            houseBasicInfo.setType(listHub.getPropertySubtype());

            houseBasicInfo.setBathrooms(listHub.getBathroomCount());
            houseBasicInfo.setBedrooms(listHub.getBedroomCount());

            houseBasicInfo.setCounty(listHub.getCounty());
            houseBasicInfo.setLiving_area(listHub.getLivingArea());
            houseBasicInfo.setLot_area(listHub.getLotSize());
            houseBasicInfo.setYear(listHub.getYearBuilt());

            houseBasicInfo.setFull_bathrooms(listHub.getFullBathroomCount());
            houseBasicInfo.setHalf_bathrooms(listHub.getHalfBathroomCount());
            houseBasicInfo.setQuarter_bathrooms(listHub.getThreeQuarterBathroomCount());
            houseBasicInfo.setMls_number(listHub.getMlsNumber());
            houseBasicInfo.setListing_price(listHub.getListPrice());
            Double average_price = null;

            if (listHub.getListPrice() != null && listHub.getListPrice() > 0) {
                if (listHub.getLivingArea() != null && listHub.getLivingArea() > 0) {
                    average_price = listHub.getListPrice() / listHub.getLivingArea();
                }
            }

            houseBasicInfo.setAverage_price(DoubleUtils.format(average_price));

            if (!StringUtils.isEmpty(listHub.getListingKey())) {
                String key = "json/" + listHub.getListingKey() + ".json";
                try {
                    OSSClient ossClient = new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
                    String json = OSSUtil.downloadJson(ossClient, ossConfig.getBacketName(), key);
                    if (!StringUtils.isEmpty(json)) {
                        net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(json);

                        //社区名称
                        if (jsonObject.get("location") != null && !jsonObject.get("location").equals("null")) {
                            net.sf.json.JSONObject location = (net.sf.json.JSONObject) jsonObject.get("location");
                            if (location.get("community") != null && !location.get("community").equals("null")) {
                                net.sf.json.JSONObject community = (net.sf.json.JSONObject) location.get("community");
                                if (community.get("communityName") != null && !community.get("communityName").equals("null")) {
                                    String communityName = community.get("communityName").toString();
                                    houseBasicInfo.setCommunity(communityName);
                                }
                            }
                        }
                        ObjectMapper mapper = new ObjectMapper();
                        //房源特征
                        if (jsonObject.get("detailedCharacteristics") != null && !jsonObject.get("detailedCharacteristics").equals("null")) {
                            net.sf.json.JSONObject characteristics = (net.sf.json.JSONObject) jsonObject.get("detailedCharacteristics");
                            if (characteristics != null && !characteristics.equals("null")) {
                                DetailedCharacteristicsType detailedCharacteristicsType = mapper.readValue(characteristics.toString(), DetailedCharacteristicsType.class);
                                //建筑风格
                                if (detailedCharacteristicsType.getArchitectureStyle() != null)
                                    houseBasicInfo.setStyle(detailedCharacteristicsType.getArchitectureStyle().getValue());
                            }
                        }

                        //税
                        if (jsonObject.get("taxes") != null && !jsonObject.get("taxes").equals("null")) {
                            net.sf.json.JSONObject taxes = (net.sf.json.JSONObject) jsonObject.get("taxes");
                            if (taxes != null && !taxes.equals("null")) {
                                ListingItemType.Taxes taxes_list = mapper.readValue(taxes.toString(), ListingItemType.Taxes.class);
                                final List<TaxType> taxs = taxes_list.getTax();
                                TaxType taxType = taxs.get(0);
                                if (taxType != null) {
                                    if (taxType.getYear() != null && taxType.getAmount() != null) {
                                        houseBasicInfo.setProperty_tax(taxType.getYear().getYear() + ":" + taxType.getAmount().getValue());
                                    }
                                }
                            }
                        }
                        //物业费
                        //Home Owner Assessments Fee
                        //额外费用
                        if (!StringUtils.isEmpty(jsonObject.get("expenses")) && !jsonObject.get("expenses").equals("null")) {
                            net.sf.json.JSONObject expenses = (net.sf.json.JSONObject) jsonObject.get("expenses");
                            if (expenses != null && !expenses.equals("null")) {
                                ListingItemType.Expenses expenses_list = mapper.readValue(expenses.toString(), ListingItemType.Expenses.class);
                                for (ExpensesType item : expenses_list.getExpense()) {
                                    String value = item.getExpenseCategory().getValue();
                                    if (!StringUtils.isEmpty(value) && value.equals("Home Owner Assessments Fee")) {
                                        //物业费
                                        houseBasicInfo.setHoa_fee(item.getExpenseValue().getValue() + "/" + item.getExpenseValue().getCurrencyPeriod());
                                        break;
                                    }
                                }
                            }
                        }

                        //预估月租金
                        //Double forecastRent = timeSeriesDataAllRentMedianService.getForecastRent(listHub.getZip(), listHub.getLivingArea());
                        //houseBasicInfo.setRent_price(DoubleUtils.format(forecastRent));

                        return new Result(ResultCode.SUCCESS, houseBasicInfo);
                    }
                } catch (net.sf.json.JSONException e) {
                    e.printStackTrace();
                } catch (JsonParseException e) {
                    e.printStackTrace();
                } catch (JsonMappingException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            return new Result(ResultCode.NO_DATA);
        }
        return new Result(ResultCode.FAIL);
    }

    @ApiOperation(value = "房源描述", notes = "房源描述", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "houseId", value = "房源ID", required = true, paramType = "path")
    })
    @GetMapping(value = "/{houseId}/description")
    public Object description(@PathVariable("houseId") String houseId) {
        House listHub = houseService.selectByPrimaryKey(houseId);
        if (listHub != null && !StringUtils.isEmpty(listHub.getListingKey())) {
            String key = "json/" + listHub.getListingKey() + ".json";
            try {
                String json = downloadService.downloadJsonFromOSS(key);
                if (!StringUtils.isEmpty(json)) {
                    JSONObject dataJson = JSONObject.parseObject(json);
                    if (dataJson.get("listingDescription") != null && !dataJson.get("listingDescription").equals("null")) {
                        String listingDescription = (String) dataJson.get("listingDescription");
                        TranslationResult translationResult = translateService.trans(houseId, listingDescription);
                        return new Result(ResultCode.SUCCESS, translationResult);
                    } else {
                        return new Result(ResultCode.NO_DATA);
                    }
                }
            } catch (net.sf.json.JSONException e) {
                e.printStackTrace();
            }
        } else {
            return new Result(ResultCode.NO_DATA);
        }
        return new Result(ResultCode.FAIL);
    }


    @ApiOperation(value = "房源图片", notes = "房源图片", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "houseId", value = "房源ID", required = true, paramType = "path")
    })
    @GetMapping(value = "/{houseId}/photos")
    public Object photo(@PathVariable("houseId") String houseId) {
        ListHubPhoto record = new ListHubPhoto();
        record.setHouseId(houseId);
        record.setIsDownload(true);
        record.setDownloadStatus(1);
        record.setRepeat(false);
        List<ListHubPhoto> list = listHubPhotoService.selectByBean(record);
        List<String> photos = new ArrayList<>();
        for (ListHubPhoto listHubPhoto : list) {
            photos.add(listHubPhoto.getOssUrl());
        }
        return new Result(ResultCode.SUCCESS, photos);
    }

    @ApiOperation(value = "房源搜索", notes = "房源搜索", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "action", value = "查询方法(zip,address,city)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "keyword", value = "查询条件", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "page", value = "页码", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "pageSize", value = "每页条数,默认20条", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "type", value = "房屋类型", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "beds", value = "卧室数量", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "baths", value = "卫浴数量", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "year", value = "房龄", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Double", name = "minSize", value = "最小面积", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Double", name = "maxSize", value = "最大面积", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Double", name = "minPrice", value = "最小价格", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Double", name = "maxPrice", value = "最大价格", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "filed", value = "排序字段(bedroomCount：卧室数量;bathroomCount：浴数量;yearBuilt：房龄;livingArea：面积;listPrice:价格)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "direction", value = "排序方向(asc：升序  desc：降序)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Double", name = "minX", value = "minX", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Double", name = "maxX", value = "maxX", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Double", name = "minY", value = "minY", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Double", name = "maxY", value = "maxY", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Boolean", name = "isNewHouse", value = "是否查询新房", required = false, paramType = "query"),

    })
    @GetMapping("/search")
    public Object search(
            @RequestParam(value = "action", defaultValue = "") String action,
            @RequestParam(value = "keyword", defaultValue = "") String keyword,
            @RequestParam(value = "page", defaultValue = "") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "") Integer pageSize,
            @RequestParam(value = "type", defaultValue = "") String type,
            @RequestParam(value = "beds", defaultValue = "") Integer beds,
            @RequestParam(value = "baths", defaultValue = "") Integer baths,
            @RequestParam(value = "year", defaultValue = "") Integer year,
            @RequestParam(value = "minSize", defaultValue = "") Double minSize,
            @RequestParam(value = "maxSize", defaultValue = "") Double maxSize,
            @RequestParam(value = "minPrice", defaultValue = "") Double minPrice,
            @RequestParam(value = "maxPrice", defaultValue = "") Double maxPrice,
            @RequestParam(value = "filed", defaultValue = "") String filed,
            @RequestParam(value = "direction", defaultValue = "asc") String direction,
            @RequestParam(value = "minX", defaultValue = "") Double minX,
            @RequestParam(value = "maxX", defaultValue = "") Double maxX,
            @RequestParam(value = "minY", defaultValue = "") Double minY,
            @RequestParam(value = "maxY", defaultValue = "") Double maxY,
            @RequestParam(value = "isNewHouse", defaultValue = "") Boolean isNewHouse
    ) {
        try {
            long btime = System.currentTimeMillis();
            if (!StringUtils.isEmpty(action) && !StringUtils.isEmpty(keyword)) {
                if (action.equalsIgnoreCase("zip")) {
                    if (keyword.length() != 5) {
                        return new ResultPage(ResultCode.HOUSE_ILLEGALITY_ZIP_CODE);
                    }
                } else if (action.equalsIgnoreCase("address")) {
                    if (keyword.length() < 3) {
                        return new ResultPage(ResultCode.HOUSE_ADDRESS_LENGTH_SHORTAGE);
                    }
                } else if (action.equalsIgnoreCase("city")) {
                    if (keyword.length() < 3) {
                        return new ResultPage(ResultCode.HOUSE_CITY_LENGTH_SHORTAGE);
                    }
                } else {
                    return new ResultPage(ResultCode.UNSUPPORTED_SEARCH_TYPE);
                }
            }

            if (StringUtils.isEmpty(page) || page < 1) {
                page = 1;
            }

            PageInfo<ListHubList> listHubLists = solrService.searchByBean(
                    action, keyword, page, pageSize, type, beds, baths, year,
                    minSize, maxSize, minPrice, maxPrice, filed, direction, null,
                    null, minX, maxX, minY, maxY, null, isNewHouse);

            if (listHubLists.getList() == null || listHubLists.getList().size() < 1) {
                return new ResultPage(ResultCode.NO_DATA);
            }

            long etime = System.currentTimeMillis();

            System.err.println("执行时间：" + (etime - btime) + "ms");


            return new ResultPage(ResultCode.SUCCESS, listHubLists);

        } catch (Exception e) {
            e.printStackTrace();
            return new ResultPage(ResultCode.FAIL);
        }
    }

    @ApiOperation(value = "房源地图搜索", notes = "房源地图搜索", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "action", value = "查询方法(zip,address,city)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "keyword", value = "查询条件", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "type", value = "房屋类型", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "beds", value = "卧室数量", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "baths", value = "卫浴数量", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "year", value = "房龄", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "minSize", value = "最小面积", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "maxSize", value = "最大面积", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "minPrice", value = "最小价格", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "maxPrice", value = "最大价格", required = false, paramType = "query"),

            @ApiImplicitParam(dataType = "Double", name = "minX", value = "minX", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Double", name = "maxX", value = "maxX", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Double", name = "minY", value = "minY", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Double", name = "maxY", value = "maxY", required = false, paramType = "query"),

            @ApiImplicitParam(dataType = "String", name = "filed", value = "排序字段(bedroomCount：卧室数量;bathroomCount：浴数量;yearBuilt：房龄;livingArea：面积;listPrice:价格)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "direction", value = "排序方向(asc：升序  desc：降序)", required = false, paramType = "query")

    })
    @GetMapping("/search/map")
    public Object searchMap(
            @RequestParam(value = "action", defaultValue = "") String action,
            @RequestParam(value = "keyword", defaultValue = "") String keyword,
            @RequestParam(value = "type", defaultValue = "") String type,
            @RequestParam(value = "beds", defaultValue = "") Integer beds,
            @RequestParam(value = "baths", defaultValue = "") Integer baths,
            @RequestParam(value = "year", defaultValue = "") Integer year,
            @RequestParam(value = "minSize", defaultValue = "") Double minSize,
            @RequestParam(value = "maxSize", defaultValue = "") Double maxSize,
            @RequestParam(value = "minPrice", defaultValue = "") Double minPrice,
            @RequestParam(value = "maxPrice", defaultValue = "") Double maxPrice,
            @RequestParam(value = "filed", defaultValue = "") String filed,
            @RequestParam(value = "direction", defaultValue = "asc") String direction,
            @RequestParam(value = "minX", defaultValue = "") Double minX,
            @RequestParam(value = "maxX", defaultValue = "") Double maxX,
            @RequestParam(value = "minY", defaultValue = "") Double minY,
            @RequestParam(value = "maxY", defaultValue = "") Double maxY
    ) {
        try {
            long btime = System.currentTimeMillis();
            if (!StringUtils.isEmpty(action) && !StringUtils.isEmpty(keyword)) {
                if (action.equalsIgnoreCase("zip")) {
                    if (keyword.length() != 5) {
                        return new ResultPage(ResultCode.HOUSE_ILLEGALITY_ZIP_CODE);
                    }
                } else if (action.equalsIgnoreCase("address")) {
                    if (keyword.length() < 3) {
                        return new ResultPage(ResultCode.HOUSE_ADDRESS_LENGTH_SHORTAGE);
                    }
                } else if (action.equalsIgnoreCase("city")) {
                    if (keyword.length() < 3) {
                        return new ResultPage(ResultCode.HOUSE_CITY_LENGTH_SHORTAGE);
                    }
                } else {
                    return new ResultPage(ResultCode.UNSUPPORTED_SEARCH_TYPE);
                }
            }

            List<HouseMap> list = solrService.searchMapByBean(action, keyword, type, beds, baths, year, minSize, maxSize, minPrice, maxPrice, filed, direction, null, null, minX, maxX, minY, maxY, null);

            long etime = System.currentTimeMillis();
            System.err.println("执行时间：" + (etime - btime) + "ms");

            if (list.size() > 0) {
                return new Result(ResultCode.SUCCESS, list);
            } else {
                return new Result(ResultCode.NO_DATA);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.FAIL);
        }
    }

    @ApiOperation(value = "搜索联想", notes = "搜索联想", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "keyword", value = "keyword", required = true, paramType = "path")
    })
    @GetMapping("/associate/{keyword}")
    public Object associate(@PathVariable(value = "keyword") String keyword) {
        if (StringUtils.isEmpty(keyword)) {
            return new Result(ResultCode.ERROR_PARAMETER);
        }
        if (keyword.length() < 3) {
            return new Result(ResultCode.ERROR_KEYWORD_LENGTH_THREE);
        }

        List<AssociateZip> zipResult = solrService.associateSearchByZip(keyword);
        List<AssociateCity> cityResult = solrService.associateSearchByCity(keyword);
        List<AssociateAddress> addressResult = solrService.associateSearchByAddress(keyword);

        AssociateResult associateResult = new AssociateResult();
        associateResult.setZip(zipResult);
        associateResult.setCity(cityResult);
        associateResult.setAddress(addressResult);

        return new Result(ResultCode.SUCCESS, associateResult);

    }

    @ApiOperation(value = "十大热门城市房源数量", notes = "十大热门城市房源数量", response = HotCityHouseCount.class, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @GetMapping(value = "/hot-city/house-count")
    public Object hotCityCount() {
        long time = System.currentTimeMillis();

//        List<HotCityHouseCount> list = new ArrayList<>();
//        List<HotCity> hotCities = hotCityService.selectAll();
//        for (HotCity hotCity : hotCities) {
//            HotCityHouseCount houseCount = new HotCityHouseCount();
//            List<String> zips = Arrays.asList(hotCity.getZipcodes().split(","));
//            ListHubParam record = new ListHubParam();
//            record.setEnabled(true);
//            record.setListingStatus("Active");
//            record.setZips(zips);
//
//            int count = houseService.selectCountByZips(record);
//            houseCount.setCity(hotCity.getEnName());
//            houseCount.setCount(count);
//
//            list.add(houseCount);
//        }
        List<HotCityHouseCount> list = hotCityService.selectHouseCount();
        System.err.println(System.currentTimeMillis() - time);
        return new Result<>(ResultCode.SUCCESS, list);
    }


    @ApiOperation(value = "视频", notes = "视频", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "houseId", value = "房源ID", required = true, paramType = "path"),
            @ApiImplicitParam(dataType = "int", name = "pageNumber", value = "页码", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "pageSize", value = "每页数量", required = false, paramType = "query")
    })
    @GetMapping("/videos/{houseId}")
    public Object videos(@PathVariable(value = "houseId") String houseId, Integer pageNumber, Integer pageSize) {
        if (StringUtils.isEmpty(houseId)) {
            return new Result(ResultCode.ERROR_PARAMETER);
        }

        //作业状态：
        //Submitted表示作业已提交，
        //Transcoding表示转码中，
        //TranscodeSuccess表示转码成功，
        //TranscodeFail表示转码失败，
        //TranscodeCancelled表示转码取消

        HouseVideo record = new HouseVideo();
        record.setStatus("TranscodeSuccess");
        record.setHouseId(houseId);
        record.setEnabled(true);
        PageInfo<HouseVideo> houseVideoPageInfo = houseVideoService.selectByBean(pageNumber, pageSize, record);

        return new ResultPage<>(ResultCode.SUCCESS, houseVideoPageInfo);

    }
}

